<?php

use App\Base\Response;
use App\Base\RouteHandle;
use App\Base\ErrCode;

define('ROOT_PATH', __DIR__);
define('RUNTIME_PATH', ROOT_PATH . DIRECTORY_SEPARATOR . 'Runtime');
define('APP_PATH', ROOT_PATH . '/App/');
define('TEMPLATE_PATH', ROOT_PATH . '/App/Public/');

include_once "vendor/autoload.php";
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 'on');


class Start
{
    use Response;

    public static function run()
    {
        (new static())->whenStart();

        include_once ROOT_PATH . '/route.php';
        $route = RouteHandle::$route;
        $action = $route[$_GET['route'] ?? ''] ?? '';

        if (empty($action)) {
            self::returnJson(ErrCode::$failCode,[], '路由不存在');
        }

        // 走中间件
        if ($middleware = RouteHandle::currentMiddleware()) {
            (new $middleware)->handle();
        }
        list($method, $className) = explode('@', $action);
        call_user_func([new $className, $method]);
    }

    public function __call($name, $arguments)
    {
    }

    public static function __callStatic($name, $arguments)
    {
    }

    public function whenStart()
    {
        $this->allowOrigin();
        $this->createRuntimeDir();
    }

    public function allowOrigin()
    {
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header(
            'Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin, JWTTOKEN'
        ); // 设置允许自定义请求头的字段
    }

    public function createRuntimeDir()
    {
        if (!is_dir(RUNTIME_PATH)) {
            mkdir(RUNTIME_PATH, 777);
        }
    }
}

Start::run();